package com.net.model.https;

import com.drug.lib.util.DLog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * Created by Administrator on 2017/6/28.
 */

public class BooleanConverterFactory extends Converter.Factory {

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        final Converter<ResponseBody, ?> delegate = retrofit.nextResponseBodyConverter(this, type, annotations);
        return new Converter<ResponseBody, Object>() {
            @Override
            public Object convert(ResponseBody body) throws IOException {
                if (body.contentLength() == 0) return null;
                String content = body.string();
                ResponseBody responseBody = ResponseBody.create(body.contentType(), content);
                try {
                    JSONObject jsonObject = new JSONObject(content);
                    Object object = jsonObject.get("data");
                    if (object instanceof Boolean && !(Boolean) object) {
                        jsonObject.put("data", null);
                        responseBody = ResponseBody.create(body.contentType(), jsonObject.toString());
                    }
                    return delegate.convert(responseBody);
                } catch (JSONException e) {
                    e.printStackTrace();
                    return delegate.convert(responseBody);
                }
            }
        };
    }
}
